package top.ucat.starter.swagger.config;

import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.paths.RelativePathProvider;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.servlet.ServletContext;
import java.util.ArrayList;
import java.util.List;

@Configuration
//@ConfigurationProperties(prefix = "ucat.swagger")
@Data
@EnableSwagger2
@RefreshScope
public class Swagger2Config {

    @Value("${ucat.swagger.basepage:}")
    private String basepage;
    @Value("${ucat.swagger.title:}")
    private String title;
    @Value("${ucat.swagger.description:}")
    private String description;
    @Value("${ucat.swagger.termsOfServiceUrl:}")
    private String termsOfServiceUrl;
    @Value("${ucat.swagger.version:}")
    private String version;
    @Value("${ucat.swagger.preUrl:}")
    private String preUrl;

    @Autowired
    private ServletContext servletContext;


    @Bean
    public Docket createRestApi() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2)

                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(basepage))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(securitySchemes());

        if (!StringUtils.isEmpty(preUrl)) {
            docket.pathProvider(new RelativePathProvider(servletContext) {
                @Override
                public String getApplicationBasePath() {
                    return preUrl;
                }
            });
        }
        return docket;
    }

    private List<ApiKey> securitySchemes() {
        List<ApiKey> apiKeyList = new ArrayList();
        apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));
        return apiKeyList;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(title)
                .description(description)
                .termsOfServiceUrl(termsOfServiceUrl)
                .version(version)
                .build();
    }
}